<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">流程名</label>
        <el-input
          v-model="query.flowName"
          clearable
          placeholder="流程名"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="500px"
        :destroy-on-close="true"
      >
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="流程名" prop="flowName">
            <el-input v-model="form.flowName" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="流程类型" prop="flowTypes.id">
            <el-select v-model="form.flowTypes.id" style="width: 370px;">
              <el-option v-for="item in allFlowType" :key="item.id" :label="item.flowType" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="图标" prop="icon">
            <el-popover
              placement="bottom-start"
              width="370"
              trigger="click"
              @show="$refs['iconSelect'].reset()"
            >
              <IconSelect ref="iconSelect" @selected="selected" />
              <el-input slot="reference" v-model="form.icon" style="width: 370px;" placeholder="点击选择图标" readonly>
                <svg-icon
                  v-if="form.icon"
                  slot="prefix"
                  :icon-class="form.icon"
                  class="el-input__icon"
                  style="height: 32px;width: 16px;"
                />
                <i v-else slot="prefix" class="el-icon-search el-input__icon" />
              </el-input>
            </el-popover>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="form.remarks" type="textarea" autosize style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="isShowFlow"
        :destroy-on-close="true"
        :modal-append-to-body="false"
        fullscreen
        @close="crud.toQuery"
      >
        <div class="custom-dialog-body">
          <SnakerFlowDesigner ref="designer" v-model="flowData" :extend-attr-config="extendAttrConfig" :show-doc="false" @on-save="handleSave">
            <!--            <template v-slot:form-item-task-performType="{model,field}">-->
            <!--              <el-form-item v-model="model[field]" label="参与类型">-->
            <!--                <el-button-group>-->
            <!--                  <el-button type="primary" icon="el-icon-orange" @click="handlePerformType('dept',model,field)">部门</el-button>-->
            <!--                  <el-button type="primary" icon="el-icon-apple" @click="handlePerformType('user',model,field)">用户</el-button>-->
            <!--                </el-button-group>-->
            <!--              </el-form-item>-->
            <!--            </template>-->
            <!--            <template v-slot:form-item-task-assignee="{model,field}">-->
            <!--              <el-form-item label="参与者">-->
            <!--                <treeselect-->
            <!--                  v-model="model[field]"-->
            <!--                  :options="depts"-->
            <!--                  :load-options="loadDepts"-->
            <!--                  style="width: 250px"-->
            <!--                  placeholder="选择部门"-->
            <!--                />-->
            <!--              </el-form-item>-->
            <!--            </template>-->
            <template v-slot:form-item-task-assignee="{model,field}">
              <el-form-item label="参与者">
                <el-select v-model="model[field]" placeholder="请选择">
                  <el-option
                    v-for="item in users"
                    :key="item.id"
                    :label="item.nickName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </template>
          </SnakerFlowDesigner>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        border
        style="width: 100%;"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="flowName" label="流程名" />
        <el-table-column prop="flowTypes" label="流程类型">
          <template slot-scope="scope">
            {{ scope.row.flowTypes.flowType }}
          </template>
        </el-table-column>
        <el-table-column prop="isDeployed" label="是否部署">
          <template slot-scope="scope">
            {{ dict.label.deploy_status[scope.row.isDeployed] }}
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" />
        <el-table-column
          v-if="checkPer(['admin','flowConfig:edit','flowConfig:del'])"
          label="操作"
          width="150px"
          align="center"
        >
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
        <el-table-column label="执行" width="150px" align="center">
          <template slot-scope="scope">
            <el-button type="text">查看</el-button>
            <el-button type="text" @click="getFlowIdFromDesign(scope.row)">设计</el-button>
            <el-button type="text" @click="taskDeploy(scope.row)">部署</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudFlowConfig, { deployProcess, editPorcess } from '@/api/flow/flowConfig'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation.vue'
import crudOperation from '@crud/CRUD.operation.vue'
import udOperation from '@crud/UD.operation.vue'
import pagination from '@crud/Pagination.vue'
import { getFlowType } from '@/api/system/flowType'
import IconSelect from '@/components/IconSelect/index.vue'
import { getDepts } from '@/api/system/dept'
import Treeselect, { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import { getUsers } from '@/api/system/user'

const defaultForm = {
  id: null,
  flowName: null,
  flowId: null,
  flowKey: null,
  flowType: null,
  icon: null,
  remarks: null,
  isDeployed: null,
  createBy: null,
  updateBy: null,
  createTime: null,
  updateTime: null,
  status: null,
  flowTypes: { id: null }
}
export default {
  name: 'FlowConfig',
  components: { Treeselect, IconSelect, pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['deploy_status'],
  cruds() {
    return CRUD({
      title: '系统：流程配置',
      url: 'api/flowConfig',
      idField: 'id',
      sort: 'id',
      crudMethod: { ...crudFlowConfig }
    })
  },
  data() {
    return {
      permission: {
        add: ['admin', 'flowConfig:add'],
        edit: ['admin', 'flowConfig:edit'],
        del: ['admin', 'flowConfig:del']

      },
      rules: {
        flowName: [
          { required: true, message: '流程名不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'flowName', display_name: '流程名' }
      ],
      depts: [],
      users: [],
      context: Object,
      isShowFlow: false,
      flowName: String,
      inputFlowName: '',
      flowXmlData: Object,
      flowData: {},
      allFlowType: [],
      isFullScreenModalOpen: false,
      scopeFlowData: Object,
      extendAttrConfig: {
        'items': [
          {
            'label': '用户标识',
            'name': 'userKey',
            'icon': '',
            'tips': '参与者处理类可根据用户标识获取参与者'
          }
        ]
      }
    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.beforeToCU]() {
      this.getFlowType()
    },
    taskDeploy(data) {
      deployProcess(data).then(res => {
        this.$message({
          message: '部署成功',
          type: 'success'
        })
        this.crud.toQuery()
      })
    },
    getFlowType() {
      getFlowType().then(res => {
        this.allFlowType = res.content
      })
    },
    // 选中图标
    selected(name) {
      this.form.icon = name
    },
    // 获取选中行数据
    getFlowIdFromDesign(data) {
      this.scopeFlowData = data
      if (data.orginalData !== undefined) {
        this.flowData = JSON.parse(data.orginalData)
      }
      getDepts({ enabled: true }).then(res => {
        this.depts = res.content.map(function(obj) {
          if (obj.hasChildren) {
            obj.children = null
          }
          obj.id = String(obj.id)
          return obj
        })
      })
      getUsers({ enabled: true }).then(res => {
        this.users = res.map(function(obj) {
          obj.id = String(obj.id)
          obj.assignee = obj.id
          return obj
        })
      })
      this.isShowFlow = true
    },
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ enabled: true, pid: parseInt(parentNode.id) }).then(res => {
          parentNode.children = res.content.map(function(obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            obj.id = String(obj.id)
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    handleSave(data) {
      const param = {
        orginalData: data.json,
        id: this.scopeFlowData.id
      }
      editPorcess(param).then(res => {
        this.$message({
          message: '保存成功',
          type: 'success'
        })
      })
    },
    handlePerformType(type, model, field) {
      model[field] = type
    }
  }
}

</script>

<style scoped>
.custom-dialog-body {
  height: calc(85vh - 60px);
  overflow: auto;
}
</style>
